package cn.com.ccxcredit.wallet.ui;

import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.util.Log;
import android.view.View;

import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.admin.methods.response.PersonalUnlockAccount;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.tx.Contract;
import org.web3j.utils.Convert;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ccxcredit.wallet.R;
import cn.com.ccxcredit.wallet.RequestInstance;
import cn.com.ccxcredit.wallet.observer.SimpleObserve;
import cn.com.ccxcredit.wallet.util.HttpUiTips;
import huixue.cn.com.library.base.SimpleActivity;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class TransferActivity extends SimpleActivity {

    @BindView(R.id.et_send_address)
    AppCompatEditText etSendAddress;
    @BindView(R.id.et_trans_coin)
    AppCompatEditText etTransCoin;
    @BindView(R.id.et_receive_address)
    AppCompatEditText etReceiveAddress;
    @BindView(R.id.btn_confirm)
    AppCompatButton btnConfirm;


    @Override
    public int getLayout() {
        return R.layout.activity_transfer;
    }

    @Override
    public void initView() {

    }

    @Override
    public void addEvent() {

    }

    @OnClick({R.id.btn_confirm})
    public void onViewClicked(View view) {
        HttpUiTips.showDialog(this,true, "loading...");
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                String msg = transferEth(etSendAddress.getText().toString().trim(),
                        "78787878",etReceiveAddress.getText().toString().trim(),
                        new BigInteger(etTransCoin.getText().toString().trim()));
                e.onNext(msg);
                //Log.d("ChannelIndex","msg=="+msg);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SimpleObserve<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                super.onSubscribe(d);
            }

            @Override
            public void onNext(String s) {
                super.onNext(s);
                HttpUiTips.showDialog(TransferActivity.this,true, "loading...");
            }
        });

    }

    public String transferEth(String from, String password, String to, BigInteger value) throws Exception {
        Admin web3j = RequestInstance._instance.admin;
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
                from, DefaultBlockParameterName.LATEST).sendAsync().get();
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();
        PersonalUnlockAccount personalUnlockAccount = web3j.personalUnlockAccount(from, password).send();
        if (personalUnlockAccount.accountUnlocked()) {
            BigInteger gasPrice = Contract.GAS_PRICE;
            BigInteger gasLimit = new BigInteger("90000");
            synchronized (TransferActivity.class) {
                Transaction transaction = Transaction.createEtherTransaction(from, nonce, gasPrice, gasLimit, to, value);
                EthSendTransaction transactionResponse = web3j.ethSendTransaction(transaction).sendAsync().get();
                if (transactionResponse.hasError()) {
                    String message=transactionResponse.getError().getMessage();
                    System.out.println("transaction failed,info:"+message);
                    return message;

                }else{
                    String hash=transactionResponse.getTransactionHash();
                    EthGetTransactionReceipt send = web3j.ethGetTransactionReceipt(hash).send();
                    System.out.println("transaction from "+from+" to "+to+" amount:"+value);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    BigInteger gas_quility = web3j.ethEstimateGas(transaction).send().getAmountUsed();
                    BigInteger gas_price = web3j.ethGasPrice().send().getGasPrice();
                    BigInteger bgasUsed = gas_quility.multiply(gas_price);
                    BigDecimal gasUsed = Convert.fromWei(bgasUsed.toString(), Convert.Unit.ETHER);
                    System.out.println("transaction gas_quility:"+gas_quility+",gas_price:"+gas_price+",gasUsed:"+gasUsed);
                    return  hash;
                }
            }
        }
        return "";
    }



}
